1. Data Types
- Create and print a logical.
l <- TRUE
print(l)
## [1] TRUE
- Create and print an integer.
i <- 123L
print(i)
## [1] 123
- Create and print a numeric.
n <- 1.23
print(n)
## [1] 1.23
- Create and print a character string.
c <- "ABC 123"
print(c)
## [1] "ABC 123"
- Create and invoke a function.
f <- function(x) { x + 1 }
f(2)
## [1] 3
2. Data Structures
- Create and print a vector.
v <- c(1, 2, 3);
print(v)
## [1] 1 2 3
- Create and print a sequence.
s <- 1:5
print(s)
## [1] 1 2 3 4 5
- Create and print a matrix.
m <- matrix(
data = 1:6,
nrow = 2,
ncol = 3)
print(m)
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
- Create and print an array.
a <- array(
data = 1:8,
dim = c(2, 2, 2))
print(a)
## , , 1
##
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## , , 2
##
## [,1] [,2]
## [1,] 5 7
## [2,] 6 8
- Create and print a list.
l <- list(TRUE, 1L, 2.34, "abc")
print(l)
## [[1]]
## [1] TRUE
##
## [[2]]
## [1] 1
##
## [[3]]
## [1] 2.34
##
## [[4]]
## [1] "abc"
- Create and print a factor.
genders <- c("Male", "Female", "Male", "Male", "Female")
factor <- factor(genders)
print(factor)
## [1] Male Female Male Male Female
## Levels: Female Male
- Print the levels of a factor
levels(factor)
## [1] "Female" "Male"
- Inspect the internals of a factor
unclass(factor)
## [1] 2 1 2 2 1
## attr(,"levels")
## [1] "Female" "Male"
3. Data Frames
- Create a data frame.
df <- data.frame(
Name = c("Cat", "Dog", "Cow", "Pig"),
HowMany = c(5, 10, 15, 20),
IsPet = c(TRUE, TRUE, FALSE, FALSE))
- Print a data frame
print(df)
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 2 Dog 10 TRUE
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Index the data frame by row and column.
df[1, 2]
## [1] 5
- Index the data frame by row.
df[1, ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
- Index the data frame by column index.
df[ , 2]
## [1] 5 10 15 20
- Index the data frame by column name.
df[["HowMany"]]
## [1] 5 10 15 20
- Index the data frame by column name (shorthand).
df$HowMany
## [1] 5 10 15 20
- Subset using a vector of indexes.
df[c(2, 4), ]
## Name HowMany IsPet
## 2 Dog 10 TRUE
## 4 Pig 20 FALSE
- Subset using a sequence of indexes.
df[2:4, ]
## Name HowMany IsPet
## 2 Dog 10 TRUE
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Subset using a vector of logicals.
df[c(TRUE, FALSE, TRUE, FALSE), ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 3 Cow 15 FALSE
- Subset using the equality operator.
df[df$IsPet == TRUE, ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 2 Dog 10 TRUE
- Subset using an inequality operator.
df[df$HowMany > 10, ]
## Name HowMany IsPet
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Subset using the match operator.
df[df$Name %in% c("Cat", "Cow"), ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 3 Cow 15 FALSE